<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\ItemCard;
use app\common\model\Order;
use app\common\model\ProfitIntegral;
use app\common\model\ProfitMoney;
use app\common\model\ProfitMoney2;
use app\common\model\ProfitPay;
use app\common\model\ProfitScore;
use app\common\model\QyLevel;
use app\common\model\User as Usermodel;
use app\common\model\UserCoupon;
use app\common\model\UserRecharge;
use app\common\model\UserVip;
use app\common\model\OrderList;
use app\common\server\LiveMoney;
use think\facade\Db;
use think\Request;
use app\common\server\Qcode;

class User extends Base
{

    /**
     * 我的
     */
    public function user(Request $request)
    {
        $user = $this->getUser();
        $userinfo['ID'] = $user['id'];
        $userinfo['mobile_is'] = $user['mobile'] ? 1 : 0;
        $userinfo['nickname'] = $user['nickname'];
        $userinfo['headimg'] = imageUrl($user['headimg']);
        $userinfo['mobile'] = $user['mobile'] ? substr_replace($user['mobile'], '****', 3, 4) : '';
        $userinfo['money'] = $user['money'];
        $userinfo['money2'] = $user['money2'];
        $userinfo['integral'] = $user['integral'];
        $userinfo['score'] = $user['score'];
        $userinfo['vip'] = $this->vip_level($user['id'], $user['vip']);
        $vip_imgurl = UserVip::field('imgurl')->where('id', '=', $userinfo['vip'])->value('imgurl');
        $userinfo['vip_imgurl'] = $vip_imgurl ? imageUrl($vip_imgurl) : 0;
        $userinfo['quan_yi_level'] = \app\common\model\User::ou_qi_level($user['ou_qi_level'],$user['ou_qi']);
        $userinfo['coupon'] = UserCoupon::where('user_id', '=', $user['id'])->where('status', '=', 1)->count();
        $base = getConfig('base');
        //是否开启集市
        // $userinfo['js_is_open'] = intval($base['js_is_open']);
        //是否显示集市
        if ($user['ou_qi_level'] >= 5){
            $userinfo['is_show_js'] = 1;
        }else{
            $userinfo['is_show_js'] = 0;
        }
        //是否开启兑换
        $userinfo['is_exchange_level'] = intval($base['is_exchange_level']);
        $userinfo['dh_is_open'] = intval($base['dh_is_open']);
        $day = floor(abs(time() - $user['addtime']) / 86400);
        $userinfo['day'] = $day;
        #客服
        $other = [
//            'recharge' => [100, 200, 500, 1000, 3000],
            'jump_appid' => $base['jump_appid'],
            'corpid' => $base['corpid'],
            'wx_link' => $base['wx_link'],
            'erweima' => imageUrl($base['erweima']),
        ];
        //主要任务
        $where = [];
        $where[] = ['is_important','=',1];
        $field = 'id,type,cate,title,number,z_number';
        $task_list = \app\common\model\TaskList::getAllList($where,$field,'sort desc,id desc');

        foreach ($task_list as $k => &$v){
            //1每日任务   2每周任务
            if ($v['type'] == 1){
                $start_time = strtotime(date('Y-m-d',time()).' 00:00:00');
                $end_time = strtotime(date('Y-m-d',time()).' 23:59:59');
            }else{
                $date = date('Y-m-d');  //当前日期
                $first = 1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
                $w = date('w', strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
                $to_day = date('Y-m-d', strtotime("$date -" . ($w ? $w - $first : 6) . ' days')); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
                $to_day2 = $to_day;
                $start_time = strtotime($to_day);
                $end_time = strtotime(date('Y-m-d', strtotime("$to_day2 + 6 days")) . ' 23:59:59');  //本周结束日期
            }
            //1邀请好友注册  2抽赏任务
            if ($v['cate'] == 1){
                $yao_count = \app\common\model\User::where([['pid','=',$user['id']],['addtime','>=',$start_time]])->count();
                if ($yao_count >= $v['number']) {
                    $v['is_complete'] = 1;
                    //进度条
                    $v['percentage'] = 100;
                    //已完成数量
                    $v['ywc_count'] = $v['number'];
                } else {
                    $v['is_complete'] = 0;
                    //进度条
                    $v['percentage'] = round(($yao_count / $v['number']) * 100);
                    //已完成数量
                    $v['ywc_count'] = $yao_count;
                }
                $v['pages'] = '/pages/user/tui-guang';
            }elseif ($v['cate'] == 2){
                //$prize_num = Order::where([['user_id','=',$user['id']],['pay_type','<',10],['status','=',1],['addtime','>=',$start_time]])->count();
                $prize_num = OrderList::where([['user_id','=',$user['id']],['order_type','<',10],['addtime','>=',$start_time]])->count();
                if ($prize_num >= $v['number']) {
                    $v['is_complete'] = 1;
                    //进度条
                    $v['percentage'] = 100;
                    //已完成数量
                    $v['ywc_count'] = $v['number'];
                } else {
                    $v['is_complete'] = 0;
                    //进度条
                    $v['percentage'] = round(($prize_num / $v['number']) * 100);
                    //已完成数量
                    $v['ywc_count'] = $prize_num;
                }
                $v['pages'] = '/pages/shouye/index';
            }
            //是否已领取
            $is_ling = Db::name('user_task_list')->field('id')->where([['user_id','=',$user['id']],['task_list_id','=',$v['id']],['addtime','>=',$start_time],['addtime','<=',$end_time]])->whereNull('deltime')->find();
            if ($is_ling){
                $v['is_complete'] = 2;
            }
        }

        return $this->renderSuccess("请求成功", compact('userinfo', 'other','task_list'));
    }

    /**
     * 修改用户信息
     */
    public function update_userinfo()
    {
        $user = $this->getUser();
        $nickname = request()->param('nickname', '');
        $headimg = request()->param('headimg', '');
        if (empty($nickname)) {
            return $this->renderError("请输入姓名");
        }
        $save = [];
        if ($nickname) {
            $save['nickname'] = $nickname;
        }
        if ($headimg) {

            if (strpos($headimg, '/storage') !== false) {
                $str = explode('/storage',$headimg);
                $save['headimg'] = '/storage'.$str[1];
            } else {
                $save['headimg'] = $headimg;
            }
        }
        $res = Usermodel::field('nickname,headimg')->where('id', '=', $user['id'])->update($save);
        if ($res) {
            return $this->renderSuccess('修改成功');
        } else {
            return $this->renderError('修改失败');
        }
    }

    /**
     * vip页面
     */
    public function vip_list(Request $request)
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $vip = $this->vip_level($user_id, $user['vip']);
        $userinfo['nickname'] = $user['nickname'];
        $userinfo['headimg'] = imageUrl($user['headimg']);
        $userinfo['vip'] = $vip;
        $userinfo['upgrade_money'] = '';
        $userinfo['notice'] = '';
        $userinfo['jin_du'] = 0;
        if ($vip < 5) {
            #累计消费
            $total_order = Order::field('order_total')
                ->where('user_id', '=', $user_id)
                ->where('status', '=', 1)
                ->where('order_type', '<', 5)
                ->sum('order_total');
            #符合升级的等级
            $condition = UserVip::field('id,condition')
                ->where('id', '>', $vip)
                ->order('id asc')
                ->find();
            $userinfo['upgrade_money'] = bcsub((string)$condition['condition'], "$total_order", 2);
            $userinfo['last_vip'] = $condition['id'];
            if ($total_order >= $condition['condition']){
                $userinfo['jin_du'] = 100;
            }else{
                $userinfo['jin_du'] = $total_order / $condition['condition'] * 100;
            }

        } else {
            $userinfo['upgrade_money'] = 0;
            $userinfo['last_vip'] = 0;
        }
        #符合升级的等级
        $data = UserVip::select()->toArray();
        foreach ($data as &$value) {
            $value['imgurl'] = imageUrl($value['imgurl']);
            if ($vip == $value['id']){
                $userinfo['notice'] = $value['notice'];
            }
        }
        return $this->renderSuccess("请求成功", compact('userinfo', 'data'));
    }

    /**
     * 会员升级
     */
    public function vip_level($user_id, $vip)
    {
        #累计消费
        $total_order = Order::field('order_total')
            ->where('user_id', '=', $user_id)
            ->where('status', '=', 1)
            ->where('order_type', '<', 5)
            ->sum('order_total');
        #符合升级的等级
        $vip_info = UserVip::field('id')
            ->where('id', '>', $vip)
            ->where('condition', '<=', $total_order)
            ->order('id desc')
            ->find();
        if ($vip_info) {
            UserModel::field('vip')->where(['id' => $user_id])->update(['vip' => $vip_info['id']]);
            return $vip_info['id'];
        } else {
            return $vip;
        }
    }


    /**
     * 潮币记录
     */
    public function profitIntegral(Request $request)
    {
        $user = $this->getUser();
        $type = request()->param('type/d', 0);
        $whe = [];
        $whe[] = ['user_id', '=', $user['id']];
        if ($type == 1) {
            $whe[] = ['change_money', '>', 0];
        } elseif ($type == 2) {
            $whe[] = ['change_money', '<', 0];
        }
        $data = ProfitIntegral::field('change_money,content,addtime')
            ->withAttr('addtime', function ($value, $data) {
                return date('Y-m-d H:i:s', (int)$data['addtime']);
            })
            ->where($whe)
            ->order('id desc')
            ->paginate(15);
        $new_data = [
            'data' => $data->items(),
            'last_page' => $data->lastPage(),
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }


    /**
     * 余额明细
     */
    public function profitMoney(Request $request)
    {
        $user = $this->getUser();
        $type = request()->param('type/d', 0);
        $whe = [];
        $whe[] = ['user_id', '=', $user['id']];
        if ($type == 1) {
            $whe[] = ['type', '<>', 4];
            $whe[] = ['change_money', '>', 0];
        } elseif ($type == 2) {
            $whe[] = ['type', '<>', 4];
            $whe[] = ['change_money', '<', 0];
        } elseif ($type == 3) {
            $whe[] = ['type', '=', 4];
        }
        $data = ProfitMoney::field('change_money,content,addtime')
            ->withAttr('addtime', function ($value, $data) {
                return date('Y-m-d H:i:s', (int)$data['addtime']);
            })
            ->where($whe)
            ->order('id desc')
            ->paginate(15);
        $new_data = [
            'data' => $data->items(),
            'last_page' => $data->lastPage(),
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }

    //集市余额明细
    public function profitMoney2(Request $request)
    {
        $user = $this->getUser();
        $type = request()->param('type/d', 0);
        $whe = [];
        $whe[] = ['user_id', '=', $user['id']];
//        if ($type == 1) {
//            $whe[] = ['type', '<>', 4];
//            $whe[] = ['change_money', '>', 0];
//        } elseif ($type == 2) {
//            $whe[] = ['type', '<>', 4];
//            $whe[] = ['change_money', '<', 0];
//        } elseif ($type == 3) {
//            $whe[] = ['type', '=', 4];
//        }
        $data = ProfitMoney2::field('change_money,content,addtime')
            ->withAttr('addtime', function ($value, $data) {
                return date('Y-m-d H:i:s', (int)$data['addtime']);
            })
            ->where($whe)
            ->order('id desc')
            ->paginate(15);
        $new_data = [
            'data' => $data->items(),
            'last_page' => $data->lastPage(),
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }

    /**
     * 积分明细
     */
    public function profitScore(Request $request)
    {
        $user = $this->getUser();
        $type = request()->param('type/d', 0);
        $whe = [];
        $whe[] = ['user_id', '=', $user['id']];
        if ($type == 1) {
            $whe[] = ['change_money', '>', 0];
        } elseif ($type == 2) {
            $whe[] = ['change_money', '<', 0];
        }
        $data = ProfitScore::field('change_money,content,addtime')
            ->withAttr('addtime', function ($value, $data) {
                return date('Y-m-d H:i:s', (int)$data['addtime']);
            })
            ->where($whe)
            ->order('id desc')
            ->paginate(15);
        $new_data = [
            'data' => $data->items(),
            'last_page' => $data->lastPage(),
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }

    /**
     * 微信支付记录
     */
    public function profitPay(Request $request)
    {
        $user = $this->getUser();
        $whe = [];
        $whe[] = ['user_id', '=', $user['id']];
        $data = ProfitPay::field('change_money,content,addtime')
            ->withAttr('addtime', function ($value, $data) {
                return date('Y-m-d H:i:s', (int)$data['addtime']);
            })
            ->where($whe)
            ->order('id desc')
            ->paginate(15);
        $new_data = [
            'data' => $data->items(),
            'last_page' => $data->lastPage(),
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }

    /**
     * 潮券明细
     */
    public function coupon_list(Request $request)
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $status = request()->param('type/d', 1);
        $where = [];
        $where[] = ['user_id', '=', $user_id];

        $order_by = 'id desc';
        if ($status == 1){
            $where[] = ['status', '=', 1];
            $order_by = 'id desc';
        }elseif ($status == 2){
            $where[] = ['status', '=', 2];
            $order_by = 'share_time desc';
        }
        $data = UserCoupon::field('id,status,level,kl_num,kl_num2,title,num')
            ->where($where)
            ->order($order_by)
            ->paginate(15)->each(function ($itme) {
                //1特级赏券  2终极赏券  3高级赏券  4普通赏券
                if ($itme['level'] == 1){
                    $itme['level_text'] = '特级赏券';
                    $itme['level_img'] = imageUrl('/shang/teji.png?');
                }elseif ($itme['level'] == 2){
                    $itme['level_text'] = '终极赏券';
                    $itme['level_img'] = imageUrl('/shang/zhongji.png?');
                }elseif ($itme['level'] == 3){
                    $itme['level_text'] = '高级赏券';
                    $itme['level_img'] = imageUrl('/shang/gaoji.png?');
                }elseif ($itme['level'] == 4){
                    $itme['level_text'] = '普通赏券';
                    $itme['level_img'] = imageUrl('/shang/putong.png?');
                }
                $itme['yi_ling'] = $itme['kl_num2'] - $itme['kl_num'];
                return $itme;
            });

        $y_count = UserCoupon::where('user_id', '=', $user_id)
            ->where('type', '=', 2)
            ->where('addtime', '>=', strtotime(date("Y-m-d", time())))
            ->count();
        $z_count = 50; //总参与次数

        $ke_hc_count = 20; //最多多少个赏券合成
        $sun_hao = '10%'; //损耗
        $user_integral = $user['integral'];

        return $this->renderSuccess("请求成功", compact('data','y_count','z_count','user_integral','ke_hc_count','sun_hao'));
    }

    /**
     * 赏券详情
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function coupon_detail(){
        $user = $this->getUser();
        $user_id = $user['id'];
        $coupon_id = request()->param("coupon_id/d", 0);
        if (empty($coupon_id)) {
            return $this->renderError("缺少必要参数");
        }
        $info = UserCoupon::field('id,level,share_time,user_id,num,kl_num2,own,own2')->where('id', '=', $coupon_id)->find();
        if (empty($info)) {
            return $this->renderError("参数错误");
        }
        $info['own2'] = round($info['own2'] - $info['own'],2);
        if ($info['level'] == 1){
            $info['level_text'] = '特级赏券';
            $info['level_img'] = imageUrl('/shang/teji.png?');
        }elseif ($info['level'] == 2){
            $info['level_text'] = '终极赏券';
            $info['level_img'] = imageUrl('/shang/zhongji.png?');
        }elseif ($info['level'] == 3){
            $info['level_text'] = '高级赏券';
            $info['level_img'] = imageUrl('/shang/gaoji.png?');
        }elseif ($info['level'] == 4){
            $info['level_text'] = '普通赏券';
            $info['level_img'] = imageUrl('/shang/putong.png?');
        }
        $info['share_time'] = $info['share_time'] ? date('Y-m-d H:i:s',$info['share_time']) : '';
        $info['yl_count'] = UserCoupon::where(['status' => 3, 'from_id' => $coupon_id])->count();
        $info['yl_integral_count'] = UserCoupon::where(['status' => 3, 'from_id' => $coupon_id])->sum('l_num');
        $share_user = Usermodel::field('nickname,headimg')->where('id',$info['user_id'])->find();
        $info['share_user_nickname'] = $share_user ? $share_user['nickname'] : '';
        $info['share_user_headimg'] = $share_user ? imageUrl($share_user['headimg']) : '';
        $yl_list = UserCoupon::alias('a')
            ->field('a.user_id,a.addtime,a.l_num,b.nickname,b.headimg')
            ->join('user b','a.user_id = b.id')
            ->where(['a.status' => 3, 'a.from_id' => $coupon_id])
            ->select();
        //手气最佳
        $yl_max = Db::name('user_coupon')
            ->alias('a')
            ->field('a.user_id,a.addtime,a.l_num,b.nickname,b.headimg')
            ->join('user b','a.user_id = b.id')
            ->where(['a.status' => 3, 'a.from_id' => $coupon_id])
            ->max('a.l_num');    
        foreach ($yl_list as $k => &$v){
            $v['headimg'] = imageUrl($v['headimg']);
            $v['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
            if ($yl_max == $v['l_num']){
                $v['lucky_king'] = 1;
            }else{
                $v['lucky_king'] = 0;
            }
        }
        $info['yl_list'] = $yl_list;

        return $this->renderSuccess('请求成功',$info);
    }

    /**
     * 潮券分享
     */
    public function coupon_share()
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $coupon_id = request()->param("coupon_id/d", 0);
        if (empty($coupon_id)) {
            return $this->renderError("缺少必要参数");
        }
        $info = UserCoupon::where([['id', '=', $coupon_id],['user_id','=',$user_id]])->find();
        if (empty($info)) {
            return $this->renderError("参数错误");
        }
        $res = [];
        Db::startTrans();
        try {
            $res[] = UserCoupon::field('status,other,kl_num,updatetime,own,share_time')
                ->where(['id' => $coupon_id])
                ->update([
                    'status' => 2,
                    'share_time' => time(),
                    'updatetime' => time()
                ]);

            if (resCheck($res)) {
                Db::commit();
                return $this->renderSuccess("分享成功");
            } else {
                Db::rollback();
                return $this->renderError("网络故障,请稍后再试");
            }
        }catch (\Exception $e){
            Db::rollback();
            return $this->renderError("网络故障,请稍后再试!");
        }

    }

    /**
     * 潮券领取
     */
    public function coupon_ling()
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $coupon_id = request()->param("coupon_id/d", 0);
writelog(11111111111,$user_id);
        if (empty($coupon_id)) {
            return $this->renderError("缺少必要参数");
        }
        $info = UserCoupon::where('id', '=', $coupon_id)->find();
        if (empty($info)) {
            return $this->renderError("参数错误");
        }
        if ($info['user_id'] == $user_id) {
            return $this->renderError("请勿开启自己的劵",[],2222);
        }
        $is_ling = UserCoupon::where('user_id', '=', $user['id'])
            ->where('type', '=', 2)
            ->where('from_id', '=', $coupon_id)
            ->find();
        if ($is_ling){
            return $this->renderError("你已经领取过了",[],2222);
        }
        $count = UserCoupon::where('user_id', '=', $user['id'])
            ->where('type', '=', 2)
            ->where('addtime', '>=', strtotime(date("Y-m-d", time())))
            ->count();

        $config = getConfig("base");
        if ($config['coupon_ling_max_ci'] && $config['coupon_ling_max_ci'] > 0) {
            if($count >= $config['coupon_ling_max_ci']){
                return $this->renderError('每天最多领取'.$config['coupon_ling_max_ci'].'次');
            }
        }
        //其他人可以获得多少
        if ($info['other'] <= 0){
            return $this->renderError("来晚了, 已经被人领完了",[],2222);
        }
        Db::startTrans();
        try {
            // $coupon = new LiveMoney($info['other'], $info['kl_num'], 0.01);   //剩余金额  可领人数    最小金额
            // $data = $coupon->handle();
            // if (count($data['items']) <= 1) {
            //     $rand_money = $data['items'][0];
            // } else {
            //     $key = mt_rand(0, count($data['items']) - 1);   //随机取数组中的一个
            //     $rand_money = $data['items'][$key];
            // }
            $rand_money_arr = $this->rand_money($info['other'],$info['kl_num'],'1');
            if (count($rand_money_arr) <= 0){
                return $this->renderError("来晚了, 已经被人领完了",[],2222);
            }
            $rand_money = $rand_money_arr[0];
            $res[] = UserCoupon::field('other')->where(['id' => $coupon_id])->dec('other',floatval($rand_money))->update();

            $res[] = UserCoupon::insert([
                'user_id' => $user_id,
                'title' => $info['title'],
                'num' => 0,
                'l_num' => $rand_money,
                'status' => 3,
                'type' => 2,
                'from_id' => $coupon_id,
                'addtime' => time(),
                'updatetime' => time(),
            ]);

            $res[] = UserCoupon::field('status,other,kl_num,updatetime,own,share_time')
                ->where(['id' => $coupon_id])
                ->dec('kl_num',1)
                ->update([
                    'updatetime' => time()
                ]);

            $res[] = Usermodel::changeIntegral($user_id, $rand_money, 3, '欧气券领取', $coupon_id);

            $kl_num = UserCoupon::field('kl_num,own')->where(['id' => $coupon_id])->find();
            if ($kl_num['own'] > 0 && $kl_num['kl_num'] > 1){
                $integral = round($info['own2'] / $info['kl_num2'],2);
                $res[] = UserCoupon::field('own')->where(['id' => $coupon_id])->dec('own',floatval($integral))->update();
                $res[] = Usermodel::changeIntegral($info['user_id'], $integral, 5, '欧气券分享', $coupon_id);
            }elseif ($kl_num['own'] > 0 && $kl_num['kl_num'] == 1){
                $res[] = UserCoupon::field('own')->where(['id' => $coupon_id])->dec('own',floatval($kl_num['own']))->update();
                $res[] = Usermodel::changeIntegral($info['user_id'], $kl_num['own'], 5, '欧气券分享', $coupon_id);
            }

            if (resCheck($res)) {
                Db::commit();
                return $this->renderSuccess("领取成功");
            } else {
                Db::rollback();
                return $this->renderError("人数过多,请稍后再试",[],2222);
            }
        }catch (\Exception $e){
            Db::rollback();
            // var_dump($e->getLine());
            return $this->renderError("人数过多,请稍后再试!",[],2222);
        }

    }
    
    /**
     * 红包随机金额
     */
    public function rand_money($total,$personal_num,$min_money=1){
//        $money_total  = $total;		//总金额
//        $personal_num = $personal_num;	//总数量
//        $min_money    = $min_money;	//最小金额
        $money_right  = $total;
        $randMoney    = [];
        for($i=1;$i<=$personal_num;$i++){
            if($money_right == $personal_num){
                $money = 1;
                $money = sprintf("%.2f",$money);
            }else{
                if($i== $personal_num){
                    $money = $money_right;
                }else{
                    $max   = $money_right  - ($personal_num - $i) * $min_money;
                    if($max < 2){
                        $max = 2;
                    }
                    $money = mt_rand((int)($min_money),(int)($max/2)) ;
                    $money = sprintf("%.2f",$money);
                }
            }
            $randMoney[] = $money;
            $money_right = $money_right - $money;
            $money_right = sprintf("%.2f",$money_right);
        }
        shuffle($randMoney);
        return $randMoney;
    }

    /**
     * 计算合成
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function coupon_ji_suan(Request $request){
        $user = $this->getUser();
        $user_id = $user['id'];
        $coupon_ids = request()->param("coupon_ids", '');
        if (empty($coupon_ids)) {
            return $this->renderError("缺少必要参数");
        }
        $coupon_ids = explode(',',trim($coupon_ids));
        if (!$coupon_ids){
            return $this->renderError("缺少必要参数!");
        }
        $sum_num = 0;
        foreach ($coupon_ids as $k => $v){
            $is_coupon = UserCoupon::where(['user_id' => $user_id, 'status' => 1, 'id' => $v])->find();
            if (!$is_coupon){
                return $this->renderError("数据错误!");
            }
            if ($is_coupon['level'] < 3){
                return $this->renderError("特级,终极赏券不能合成");
            }
            $sum_num += $is_coupon['num'];
        }
        //合成损耗10%
        $sh_num = $sum_num - $sum_num * (10 / 100);
        if ($sum_num <= 0){
            return $this->renderError("网络故障,请稍后再试!!");
        }

        if (count($coupon_ids) > 20){
            return $this->renderError("最多只能20个合成");
        }

        $coupon = [];
        if ($sum_num > 0 && $sum_num < 500){
            $coupon['title'] = "普通赏券";
            $coupon['level'] = 4;
        }elseif ($sum_num >= 500 && $sum_num < 2000){
            $coupon['title'] = "高级赏券";
            $coupon['level'] = 3;
        }elseif ($sum_num >= 2000 && $sum_num < 5000){
            $coupon['title'] = "终极赏券";
            $coupon['level'] = 2;
        }elseif ($sum_num >= 5000){
            $coupon['title'] = "特级赏券";
            $coupon['level'] = 1;
        }else{
            return $this->renderError("网络故障,请稍后再试!");
        }

        return $this->renderSuccess('请求成功',compact('coupon','sum_num','sh_num'));
    }

    /**
     * 合成
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function coupon_synthesis(){
        $user = $this->getUser();
        $user_id = $user['id'];
        $coupon_ids = request()->param("coupon_ids", '');
        if (empty($coupon_ids)) {
            return $this->renderError("缺少必要参数");
        }
        $coupon_ids = explode(',',trim($coupon_ids));
        if (!$coupon_ids){
            return $this->renderError("缺少必要参数!");
        }
        $sum_num = 0;
        foreach ($coupon_ids as $k => $v){
            $is_coupon = UserCoupon::where(['user_id' => $user_id, 'status' => 1, 'id' => $v])->find();
            if (!$is_coupon){
                return $this->renderError("数据错误!");
            }
            if ($is_coupon['level'] < 3){
                return $this->renderError("特级,终极赏券不能合成");
            }
            $sum_num += $is_coupon['num'];
        }

        $coupon = [];
        $config = getConfig("base");
        if ($sum_num > 0 && $sum_num < 500){
            $coupon['title'] = "普通赏券";
            $coupon['level'] = 4;
            $coupon['kl_num'] = $config['coupon_d_xz_max'];
        }elseif ($sum_num >= 500 && $sum_num < 2000){
            $coupon['title'] = "高级赏券";
            $coupon['level'] = 3;
            $coupon['kl_num'] = $config['coupon_c_xz_max'];
        }elseif ($sum_num >= 2000 && $sum_num < 5000){
            $coupon['title'] = "终极赏券";
            $coupon['level'] = 2;
            $coupon['kl_num'] = $config['coupon_b_xz_max'];
        }elseif ($sum_num >= 5000){
            $coupon['title'] = "特级赏券";
            $coupon['level'] = 1;
            $coupon['kl_num'] = $config['coupon_a_xz_max'];
        }else{
            return $this->renderError("网络故障,请稍后再试!");
        }
        //合成损耗10%
        $sum_num = $sum_num - $sum_num * (10 / 100);
        if ($sum_num <= 0){
            return $this->renderError("网络故障,请稍后再试!!");
        }
        $coupon['num'] = $sum_num;

        //自己获得80%
        $percentage = 80;
        $own = $coupon['num'] * ($percentage / 100);
        //其他人获得20%
        $percentage = 20;
        $other = $coupon['num'] * ($percentage / 100);
        if ($own <= 0 || $other <= 0){
            return $this->renderError("网络故障,请稍后再试!!!");
        }
        Db::startTrans();
        $res = [];
        $res[] = UserCoupon::field('status,updatetime')
            ->where(['user_id' => $user_id])
            ->whereIn('id',implode(',',$coupon_ids))
            ->update([
                'status' => 4,
                'updatetime' => time()
            ]);

        $res[] = UserCoupon::insert([
            'user_id' => $user_id,
            'level' => $coupon['level'],
            'title' => $coupon['title'],
            'num' => $coupon['num'],
            'status' => 1,
            'type' => 3,
            'from_id' => 0,
            'own' => intval($own),
            'own2' => intval($own),
            'other' => intval($other),
            'other2' => intval($other),
            'kl_num' => $coupon['kl_num'],
            'kl_num2' => $coupon['kl_num'],
            'addtime' => time(),
            'updatetime' => time(),
        ]);
        if (resCheck($res)) {
            Db::commit();
            return $this->renderSuccess("融合成功");
        } else {
            Db::rollback();
            return $this->renderError("网络故障,请稍后再试");
        }
    }

    /**
     * 潮券开劵
     */
//    public function coupon_open()
//    {
//        $user = $this->getUser();
//        $user_id = $user['id'];
//        $coupon_id = request()->param("coupon_id/d", 0);
//        if (empty($coupon_id)) {
//            return $this->renderError("缺少必要参数");
//        }
//        $info = UserCoupon::where('id', '=', $coupon_id)->where('user_id', '=', $user_id)->find();
//        if (empty($info)) {
//            return $this->renderError("参数错误");
//        }
//        if ($info['status'] == 3) {
//            return $this->renderError("该劵已打开");
//        }
//        if ($info['status'] != 2) {
//            return $this->renderError("状态异常");
//        }
//        #随机数量
//        $rand_num = rand($info['min'], $info['max']);
//        Db::startTrans();
//        $res[] = UserCoupon::field('status,num,open_time')->where(['id' => $coupon_id])->update([
//            'status' => 3,
//            'num' => $rand_num,
//            'open_time' => time(),
//        ]);
//        if ($rand_num > 0) {
//            $res[] = Usermodel::changeIntegral($user_id, $rand_num, 3, '开券获得');
//        }
//        if (resCheck($res)) {
//            Db::commit();
//            return $this->renderSuccess("请求成功", $rand_num);
//        } else {
//            Db::rollback();
//            return $this->renderError("网络故障，请稍后重试");
//        }
//    }

    /**
     * 我的推广
     */
    public function invitation()
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $data = Usermodel::field('id,nickname,headimg,addtime,pid')
            ->append(['commission_money'])
            ->withAttr('addtime', function ($value, $data) {
                return date('Y-m-d H:i:s', $value);
            })
            ->where("pid", '=', $user_id)
            ->where('status', '=', 1)
            ->order("id desc")
            ->paginate(15);
        #奖励金额
        $money = ProfitMoney::field('change_money')
            ->where('user_id', '=', $user_id)
            ->where('type', '=', 5)
            ->where('change_money', '>', 0)
            ->sum('change_money');
        #配置
        $rule = getConfig('base');
        $share_image = $this->product_img();
        $new_data = [
            'share_title' => $rule['share_title'],
            'share_image' => $share_image,
            'count' => $data->total(),
            'money' => $money,
            'data' => $data->items(),
            'last_page' => $data->lastPage(),
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }
    
    
    
    /*
        海报生成器
    
    */
    public function product_img(){
         #海报名称
        $user_info = $this->getUser();
        $user_id = $user_info['id'];
        $share_image = $user_id . '.png';
        #根目录
        $public_path = dirname($_SERVER['SCRIPT_FILENAME']);
        $path = '/storage/poster/share/';
        #海报完整路径
        $save_path = $public_path . $path . $share_image;
        
         if (!file_exists($save_path)) {
            if (!file_exists($public_path . $path)) {
                mkdir($public_path . $path);
            }
    
            #小程序二维码 生成 缩放
            $param = [
                'scene' => $user_info['id'],
                'page' => 'pages/shouye/index',
                'check_path' => false,
                'env_version' => 'trial',#要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
                //'env_version' => 'release',#要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
                'width' => '340px',#默认430，二维码的宽度，单位 px，最小 280px，最大 1280px
            ];
              
            $wxServer = new \app\common\server\Wx($this->app);
            
            $wxServer->GetShareCode($param, $save_path);
           
             thumbImage($save_path, 288, 288);
            #背景图
            $share_image = getConfig("base")['share_image'];
            $poster_bg = $public_path . $share_image;
            
          
            #生成带背景的海报
            (new Qcode())->setBgCode($save_path, $poster_bg, 104, 1180);
            
        }
        #海报图片
        $share_image = request()->domain() . $path . $share_image;
      
        return $share_image;
    }

    /*
     * 佣金明细
     */
    public function invitation_commission(Request $request)
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        $data = ProfitMoney::field('change_money,addtime,content')
            ->withAttr('addtime', function ($value, $data) {
                return date('Y-m-d H:i:s', $value);
            })
            ->where("user_id", '=', $user_id)
            ->where(['type' => 5])
            ->order("id desc")
            ->paginate(15);
        $new_data = [
            'data' => $data->items(),
            'last_page' => $data->lastPage(),
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }


    /**
     * 充值
     */
    public function recharge()
    {

        $user = $this->getUser();
        if (empty($user['mobile'])) {
            return $this->renderError('请先绑定手机号', [], -9);
        }
        $money = request()->param('money', 0);
        if (empty($money)) {
            return $this->renderError("请输入充值金额");
        }
        if (RegMoney($money)) {
            return $this->renderError("充值金额输入不合法");
        }
        $config = getConfig('base');
        if ($money < $config['recharge_money']) {
            return $this->renderError("充值金额最低" . $config['recharge_money'] . '起');
        }
        #订单号
        $order_num = create_order_no('CZ_', 'user_recharge', 'order_num');
        $res = UserRecharge::insert([
            'user_id' => $user['id'],
            'order_num' => $order_num,
            'money' => $money,
            'status' => 1,
            'addtime' => time(),
        ]);
        $body = '充值金额' . $money;
        $attach = 'user_recharge';
        $payRes = (new Pay())->wxCreateOrder($order_num, $money, $user['openid'], $body, $attach);
        if ($payRes['status'] != 1) {
            Db::rollback();
            return $this->renderError("下单失败");
        }
        if ($res) {
            return $this->renderSuccess("请求成功", $payRes['data']);
        } else {
            return $this->renderError("网络故障，请稍后重试");
        }
    }

    /**
     * 重抽卡列表
     * @return \think\response\Json
     */
    public function item_card_list(){
        $user = $this->getUser();

        $list = Db::name('user_item_card')
            ->where(['user_id' => $user['id'], 'status' => 1])
            ->field('id,type,title,addtime')
            ->order('id desc')
            ->paginate(['list_rows'=>20,'query' => request()->param()]);

        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['count']=$list->total();
        $data['last_page']=$list->toArray()['last_page'];
        $data['page']=$page;

        foreach ($data['list'] as $k => &$v){
            $v['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
        }

        return $this->renderSuccess('请求成功',$data);
    }

}